package com.sandy.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LindTokenAuthenticationFilter extends OncePerRequestFilter {

    String tokenHead = "Bearer ";
    String tokenHeader = "Authorization";
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * token filter.
     *
     * @param request     .
     * @param response    .
     * @param filterChain .
     */
    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {
            // 401 Unauthorized
            response.setStatus(401);
            return;
        }
        if (token != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            String username = token;
            try {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                //可以校验token和username是否有效，目前由于token对应username存在redis，都以默认都是有效的
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                logger.info("authenticated user " + username + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (UsernameNotFoundException e) {
                // 403 Forbidden
                response.setStatus(403);
                return;
            }
        }

        filterChain.doFilter(request, response);
    }
}